package com.netty.websocket.netty;

import io.netty.channel.Channel;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.util.concurrent.ConcurrentHashMap;

/**
 * @ClassName: NettyConfig
 * @Description:netty常量类
 * @author yuyehong@cloudwalk.cn
 * @date 2020年4月29日 上午1:21:52
 * @version v1.3.0
 * @since 1.8
 */
public class NettyConfig {

	/**
	 * 定义一个channel组，管理所有的channel GlobalEventExecutor.INSTANCE 是全局的事件执行器，是一个单例
	 */
	private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

	/**
	 * 存放通道和通道对应信息，用户寻找指定通道信息
	 */
	private static ConcurrentHashMap<String, Channel> channelMap = new ConcurrentHashMap<>();

	private NettyConfig() {

	}

	/**
	 * 获取channel组
	 * @return
	 */
	public static ChannelGroup getChannelGroup() {
		return channelGroup;
	}

	public static void addChannel(Channel channel) {
		channelGroup.add(channel);
		channelMap.put(channel.id().asLongText(), channel);
	}

	public static void removeChannel(Channel channel) {
		channelGroup.remove(channel);
		channelMap.remove(channel.id().asLongText());
	}

	public static Channel findChannel(String id) {
		return channelMap.get(id);
	}

	public static void send2All(TextWebSocketFrame tws) {
		channelGroup.writeAndFlush(tws);
	}

}
